<?php
!defined( 'IN_HDWIKI' ) && exit( 'Access Denied' );
define( 'MB_RETURN_FORMAT' , 'json' );
define( 'MB_API_HOST' , 'open.t.qq.com' );

class socialconnectmodel
{
	var $db;
	var $base;

	function socialconnectmodel( & $base )
	{
		$this->base = $base;
		$this->db = $base->db;
	}
	
	function install()
	{
		$sql="CREATE TABLE IF NOT EXISTS ".DB_TABLEPRE."socialconnect (
			`uid` mediumint(8) unsigned NOT NULL,
			`sina_user_id` int(11) unsigned DEFAULT '0',
			`sina_oauth_token` varchar(64) DEFAULT '',
			`sina_oauth_token_secret` varchar(64) DEFAULT '',
			`sina_setting` tinyint(4) DEFAULT '0',
			`qq_user_name` varchar(30) DEFAULT '',
			`qq_oauth_token` varchar(64) DEFAULT '',
			`qq_oauth_token_secret` varchar(64) DEFAULT '',
			`qq_setting` tinyint(4) DEFAULT '0',
			KEY `uid` (`uid`),
			KEY `sina_user_id` (`sina_user_id`),
			KEY	`qq_user_name` (`qq_user_name`)
			) ENGINE=MyISAM DEFAULT CHARSET=".DB_CHARSET.";";
		$this->db->query( $sql );

		$r = $this->db->fetch_by_field( 'regular', 'name', 'socialconnect' );
		if ( !$r ) {
			$this->base->load( 'regular' );
			$regularexpr = 'socialconnect-default|sina-oauth|qq-oauth|sina-unbind|qq-unbind';
			$_ENV['regular']->add_regular( 'socialconnect', $regularexpr, 19 );
		}

		$plugin=array(
			'name'			=> 'SocialConnect',
			'identifier'	=> 'socialconnect',
			'description'	=> '可以通过‘新浪微博‘、’QQ微博‘来一键登录，也可以在用户设置的情况行对编辑的词条进行分享',
			'datatables'	=> '',
			'type'			=> '0',
			'copyright'		=> 'www.iAndroid.info',
			'homepage'		=> 'http://www.iandroid.info',
			'version'		=> '1.0',
			'suit'			=> '5.0',
			'modules'		=> ''
		);
		$plugin['vars'] = array(
			array(
				'displayorder'	=> '0',
				'title'			=> '开启新浪微博连接',
				'description'	=> '',
				'variable'		=> 'sina_connect_on',
				'type'			=> 'radio',
				'value'			=> '0',
				'extra'			=> ''
			),
			array(
				'displayorder'	=> '1',
				'title'			=> '新浪微博 App Key',
				'description'	=> '到 <a href="http://open.t.sina.com.cn/apps" target="_blank">http://open.t.sina.com.cn/apps</a> 申请',
				'variable'		=> 'sina_app_key',
				'type'			=> 'text',
				'value'			=> '',
				'extra'			=> ''
			),
			array(
				'displayorder'	=> '2',
				'title'			=> '新浪微博 App Secret',
				'description'	=> '到 <a href="http://open.t.sina.com.cn/apps" target="_blank">http://open.t.sina.com.cn/apps</a> 申请',
				'variable'		=> 'sina_secret_key',
				'type'			=> 'text',
				'value'			=> '',
				'extra'			=> ''
			),
			array(
				'displayorder'	=> '3',
				'title'			=> '开启 QQ 微博连接',
				'description'	=> '',
				'variable'		=> 'qq_connect_on',
				'type'			=> 'radio',
				'value'			=> '0',
				'extra'			=> ''
			),
			array(
				'displayorder'	=> '4',
				'title'			=> 'QQ 微博 App Key',
				'description'	=> '到 <a href="http://open.t.qq.com/apps_welcome.php" target="_blank">http://open.t.qq.com/apps_welcome.php</a> 申请',
				'variable'		=> 'qq_app_key',
				'type'			=> 'text',
				'value'			=> '',
				'extra'			=> ''
			),
			array(
				'displayorder'	=> '5',
				'title'			=> 'QQ 微博 App Secret',
				'description'	=> '到 <a href="http://open.t.qq.com/apps_welcome.php" target="_blank">http://open.t.qq.com/apps_welcome.php</a> 申请',
				'variable'		=> 'qq_secret_key',
				'type'			=> 'text',
				'value'			=> '',
				'extra'			=> ''
			)
		);
		$plugin['hooks'] = array(
			array(
				'available'		=> '1',
				'title'			=> 'socialconnect_nav',
				'description'	=> 'socialconnect_nav',
				'code'			=> '
					$this->load( "plugin" );
					$this->loadplugin( "socialconnect" );
					if ( $this->plugin["socialconnect"]["available"] ) {
						$sina_connect_on = $this->plugin["socialconnect"]["vars"]["sina_connect_on"];
						$qq_connect_on = $this->plugin["socialconnect"]["vars"]["qq_connect_on"];
						if ( $sina_connect_on || $qq_connect_on ) {
							$socialconnect_nav = $_ENV["socialconnect"]->get_socialconnect_nav();
							$this->view->assign( "socialconnect_nav", $socialconnect_nav );
						}
					}
				'
			),
			array(
				'available'		=> '1',
				'title'			=> 'socialconnect_login_html',
				'description'	=> 'socialconnect_login_html',
				'code'			=> '
					$this->load( "plugin" );
					$this->loadplugin( "socialconnect" );
					if ( $this->plugin["socialconnect"]["available"] ) {
						$sina_connect_on = $this->plugin["socialconnect"]["vars"]["sina_connect_on"];
						$qq_connect_on = $this->plugin["socialconnect"]["vars"]["qq_connect_on"];
						if ( $sina_connect_on || $qq_connect_on ) {
							$socialconnect_login_html_h = $_ENV["socialconnect"]->get_socialconnect_login_html_h();
							$socialconnect_login_html_v = $_ENV["socialconnect"]->get_socialconnect_login_html_v();
							$this->view->assign( "socialconnect_login_html_h", $socialconnect_login_html_h );
							$this->view->assign( "socialconnect_login_html_v", $socialconnect_login_html_v );
						}
					}
				'
			),
			array(
				'available'		=> '1',
				'title'			=> 'socialconnect_callback_to_user_login',
				'description'	=> 'socialconnect_callback',
				'code'			=> '
					$this->load( "plugin" );
					$this->loadplugin( "socialconnect" );
					if ( $this->plugin["socialconnect"]["available"] ) {
						$sina_connect_on = $this->plugin["socialconnect"]["vars"]["sina_connect_on"];
						$qq_connect_on = $this->plugin["socialconnect"]["vars"]["qq_connect_on"];
						if ( isset( $_REQUEST["callback_from"] ) ) {
							if ( $sina_connect_on && $_REQUEST["callback_from"] == "sina" )
							{
								session_start();
								$keys = $_SESSION["sina_oauth_keys"];
								unset( $_SESSION["sina_oauth_keys"] );
								if ( !$keys ) {
									$this->header();
								}
								$last_keys = $_ENV["socialconnect"]->get_sina_last_keys( $keys, $_REQUEST["oauth_verifier"] );

								if ( $_REQUEST["oauth_action"] == "bind" ) { //绑定请求
									if ( $_ENV["user"]->is_login() ) { //已登录,则绑定，然后跳转到 plugin-socialconnect 页
										$this->loadplugin( "sina", "socialconnect" );
										$_ENV["sina"]->bind( $this->user["uid"], $last_keys );
										$this->header( "plugin-socialconnect" );
										exit;

									} else { //未登录，则让用户进行 注册并绑定|或登录并绑定
										$_SESSION["sina_last_keys"] = $last_keys;
										$info = $_ENV["socialconnect"]->get_sina_user_infos( $last_keys );
										$this->view->assign( "avatar_url", $info["profile_image_url"] );
										$this->view->assign( "oauth_from", "sina" );
										$_ENV["socialconnect"]->append_lang( $this->view, "zh", "socialconnect" );
										$this->view->display( "file://plugins/socialconnect/view/callback" );
										exit;
									}
								}

								if ( $_ENV["user"]->is_login() ) { //非绑定请求，已登录，则跳转的到首页
									$this->header();
								} else { //未登录，判断数据库中是否有已绑定的用户
									$r = $this->db->fetch_by_field( "socialconnect", "sina_user_id", $last_keys["user_id"] );

									if ( !$r ) { //没有绑定的用户，则让用户进行 注册并绑定|登录并绑定
										$_SESSION["sina_last_keys"] = $last_keys;
										$info = $_ENV["socialconnect"]->get_sina_user_infos( $last_keys );
										$this->view->assign( "avatar_url", $info["profile_image_url"] );
										$this->view->assign( "oauth_from", "sina" );
										$_ENV["socialconnect"]->append_lang( $this->view, "zh", "socialconnect" );
										$this->view->display( "file://plugins/socialconnect/view/callback" );
										exit;

									} else { //找到绑定用户，则进行登录
										$this->loadplugin( "sina", "socialconnect" );
										$_ENV["sina"]->update_oauth_keys( $last_keys );
										$this->post["submit"] = $this->view->lang["login"];
										$this->oauth_login = "sina";
										$this->oauth_login_uid = $r["uid"];
									}
								}

							} else if ( $qq_connect_on && $_REQUEST["callback_from"] == "qq" ) {
								session_start();
								$keys = $_SESSION["qq_oauth_keys"];
								unset( $_SESSION["qq_oauth_keys"] );
								if ( !$keys ) {
									$this->header();
								}
								$last_keys = $_ENV["socialconnect"]->get_qq_last_keys( $keys, $_REQUEST["oauth_verifier"] );

								if ( $_REQUEST["oauth_action"] == "bind" ) { //绑定请求
									if ( $_ENV["user"]->is_login() ) { //已登录,则绑定，然后跳转到 plugin-socialconnect 页
										$this->loadplugin( "qq", "socialconnect" );
										$_ENV["qq"]->bind( $this->user["uid"], $last_keys );
										$this->header( "plugin-socialconnect" );
										exit;

									} else { //未登录，则让用户进行 注册并绑定|或登录并绑定
										$_SESSION["qq_last_keys"] = $last_keys;
										$info = $_ENV["socialconnect"]->get_qq_user_infos( $last_keys );
										$this->view->assign( "avatar_url", $info["head"] );
										$this->view->assign( "oauth_from", "qq" );
										$_ENV["socialconnect"]->append_lang( $this->view, "zh", "socialconnect" );
										$this->view->display( "file://plugins/socialconnect/view/callback" );
										exit;
									}
								}

								if ( $_ENV["user"]->is_login() ) { //非绑定请求，已登录，则跳转的到首页
									$this->header();
								} else { //未登录，判断数据库中是否有已绑定的用户
									$r = $this->db->fetch_by_field( "socialconnect", "qq_user_name", $last_keys["name"] );

									if ( !$r ) { //没有绑定的用户，则让用户进行 注册并绑定|登录并绑定
										$_SESSION["qq_last_keys"] = $last_keys;
										$info = $_ENV["socialconnect"]->get_qq_user_infos( $last_keys );
										$this->view->assign( "avatar_url", $info["head"] );
										$this->view->assign( "oauth_from", "qq" );
										$_ENV["socialconnect"]->append_lang( $this->view, "zh", "socialconnect" );
										$this->view->display( "file://plugins/socialconnect/view/callback" );
										exit;

									} else { //找到绑定用户，则进行登录
										$this->loadplugin( "qq", "socialconnect" );
										$_ENV["qq"]->update_oauth_keys( $last_keys );
										$this->post["submit"] = $this->view->lang["login"];
										$this->oauth_login = "qq";
										$this->oauth_login_uid = $r["uid"];
									}
								}
							}
						}
					}
				'
			),
			array(
				'available'		=> '1',
				'title'			=> 'socialconnect_callback_to_user_login_next',
				'description'	=> 'socialconnect_login_html',
				'code'			=> '
					$this->load( "plugin" );
					$this->loadplugin( "socialconnect" );
					if ( isset( $this->oauth_login ) && $this->plugin["socialconnect"]["available"] ) {
						if ( $this->oauth_login == "sina" ) {
							$user = $this->db->fetch_by_field( "user", "uid", $this->oauth_login_uid );
							$username = $user["username"];
							$password = $user["password"];
							$error = "OK";
								
						} else if ( $this->oauth_login == "qq" ) {
							$user = $this->db->fetch_by_field( "user", "uid", $this->oauth_login_uid );
							$username = $user["username"];
							$password = $user["password"];
							$error = "OK";
						}
					}
				'
			),
			array(
				'available'		=> '1',
				'title'			=> 'socialconnect_bind',
				'description'	=> 'socialconnect_login_html',
				'code'			=> '
					$this->load( "plugin" );
					$this->loadplugin( "socialconnect" );
					if ( isset( $this->post["tobind"] ) && $this->plugin["socialconnect"]["available"] ) {
						session_start();
						$sina_connect_on = $this->plugin["socialconnect"]["vars"]["sina_connect_on"];
						$qq_connect_on = $this->plugin["socialconnect"]["vars"]["qq_connect_on"];

						if ( isset( $_SESSION["sina_last_keys"] ) && $this->post["tobind"] == "sina" && $sina_connect_on ) {
							$last_keys = $_SESSION["sina_last_keys"];
							$this->loadplugin( "sina", "socialconnect" );
							$_ENV["sina"]->bind( $this->user["uid"], $last_keys );
							$this->header( "plugin-socialconnect" );

						} else if ( isset( $_SESSION["qq_last_keys"] ) && $this->post["tobind"] == "qq" && $qq_connect_on ) {
							$last_keys = $_SESSION["qq_last_keys"];
							$this->loadplugin( "qq", "socialconnect" );
							$_ENV["qq"]->bind( $this->user["uid"], $last_keys );
							$this->header( "plugin-socialconnect" );
						}
					}
				'
			)
		);

		return $plugin;
	}

	function uninstall()
	{
		$this->db->query( "DROP TABLE IF EXISTS ".DB_TABLEPRE."socialconnect" );
		$r = $this->db->fetch_by_field( 'regular', 'name', 'socialconnect' );
		if ( $r ) {
			$this->db->query( "DELETE FROM ".DB_TABLEPRE."regular WHERE name = 'socialconnect'" );
		}

	}

	static function append_lang( & $view, $langtype, $filename )
	{
		include HDWIKI_ROOT.'/plugins/socialconnect/lang/'.$langtype.'/'.$filename.'.php';
		$view->lang =& array_merge( $view->lang, $lang );
	}

	function get_socialconnect_nav()
	{
		$this->append_lang( $this->base->view, 'zh', 'socialconnect' );
		$html = <<<EXTRA
<li><a href="{$this->base->view->url( 'plugin-socialconnect' )}" target="_self"><img src="plugins/socialconnect/style/socialconnect.jpg" />{$this->base->view->lang( 'socialconnect' )}</a></li>
EXTRA;
		return $html;
	}

	function get_socialconnect_login_html_h()
	{

		$html = <<<EXTRA
<div>
<ul><li>
	<a href="{$this->base->view->url( 'plugin-socialconnect-sina-oauth' )}"><img src="plugins/socialconnect/style/sina_login.gif" /></a>
	<a href="{$this->base->view->url( 'plugin-socialconnect-qq-oauth' )}"><img src="plugins/socialconnect/style/qq_login.png" /></a>
</li></ul>
</div>
EXTRA;
		return $html;
	}

	function get_socialconnect_login_html_v()
	{
		$html = <<<EXTRA
<div>
<ul>
	<li><a href="{$this->base->view->url( 'plugin-socialconnect-sina-oauth' )}"><img src="plugins/socialconnect/style/sina_login.gif" /></a></li>
	<li><a href="{$this->base->view->url( 'plugin-socialconnect-qq-oauth' )}"><img src="plugins/socialconnect/style/qq_login.png" /></a></li>
</ul>
</div>
EXTRA;
		return $html;
	}

	function get_sina_last_keys( $keys, $oauth_verifier )
	{
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/sina/weibooauth.php' );

		$akey = $this->base->plugin['socialconnect']['vars']['sina_app_key'];
		$skey = $this->base->plugin['socialconnect']['vars']['sina_secret_key'];

		$o = new WeiboOAuth( $akey, $skey, $keys['oauth_token'], $keys['oauth_token_secret'] );
		$last_keys = $o->getAccessToken( $oauth_verifier );

		return $last_keys;
	}

	function get_sina_user_infos( $last_keys )
	{
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/sina/weibooauth.php' );

		$akey = $this->base->plugin['socialconnect']['vars']['sina_app_key'];
		$skey = $this->base->plugin['socialconnect']['vars']['sina_secret_key'];

		$c = new WeiboClient( $akey, $skey, $last_keys['oauth_token'], $last_keys['oauth_token_secret'] );
		$me = $c->verify_credentials();

		return $me;
	}

	function get_qq_last_keys( $keys, $oauth_verifier )
	{
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/oauth.php' );
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/opent.php' );
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/api_client.php' );

		$akey = $this->base->plugin['socialconnect']['vars']['qq_app_key'];
		$skey = $this->base->plugin['socialconnect']['vars']['qq_secret_key'];

		$o = new MBOpenTOAuth( $akey, $skey, $keys['oauth_token'], $keys['oauth_token_secret'] );
		$last_keys = $o->getAccessToken( $oauth_verifier );

		return $last_keys;
	}

	function get_qq_user_infos( $last_keys )
	{
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/oauth.php' );
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/opent.php' );
		include_once( HDWIKI_ROOT . '/plugins/socialconnect/lib/qq/api_client.php' );

		$akey = $this->base->plugin['socialconnect']['vars']['qq_app_key'];
		$skey = $this->base->plugin['socialconnect']['vars']['qq_secret_key'];

		$c = new MBApiClient( $akey, $skey, $last_keys['oauth_token'], $last_keys['oauth_token_secret'] );
		$me = $c->getUserInfo();
		$me['data']['head'] .= '/50';

		return $me['data'];
	}
}
?>
